package com.five.matebook.activity.columeedit;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.five.matebook.R;
import com.five.matebook.activity.BaseRecordActivity;
import com.five.matebook.utils.StringTreeParser;

import java.util.ArrayList;
import java.util.List;

public class CustomEditActivity extends BaseRecordActivity implements EditItemView.IOperateCallback {
    private static final String TAG = CustomEditActivity.class.getSimpleName();
    private EditItemView editItemView;
    private TextView mTxtRestore;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_edit);
        editItemView = findViewById(R.id.edit_item_view);
        mTxtRestore = findViewById(R.id.txt_restore);
        editItemView.setOperateCallback(this);
        init();
        updateChildUi();
    }

    private String mEditFiled;
    private int mLevel = 0;
    private int mResIdOfDefaultArrary = 0;
    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            mEditFiled = intent.getStringExtra("filed");
            mLevel = intent.getIntExtra("level", 0);
            mResIdOfDefaultArrary = intent.getIntExtra("resId", 0);
        }

        if (TextUtils.isEmpty(mEditFiled) || mLevel <= 0 || mResIdOfDefaultArrary <= 0) {
            Toast.makeText(this, "缺少要编辑的filed信息", Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }

        StringTreeParser parser = getStringTreeParser(mEditFiled, mResIdOfDefaultArrary, mLevel);
        for (StringTreeParser.StringItem item : parser.getArray(1, false)) {
            add(editItemView, item);
        }
    }

    private void add(EditItemView parent, StringTreeParser.StringItem item) {
        EditItemView newView = parent.addOneSub(item.toString());
        for (StringTreeParser.StringItem sub : item.getSubList()) {
            add(newView, sub);
        }
    }

    @Override
    protected void updateChildUi() {
        synchronized (this) {
            int size = operateList.size();
            mTxtRestore.setEnabled(size != 0);
            if (size == 0) {
                mTxtRestore.setText("撤销上一步");
            } else {
                mTxtRestore.setText(String.format("撤销上一步 (%d)", size));
            }
        }
    }

    public void onClick_doSave(View v) {
        editItemView.clearFocus();
        String tips = editItemView.checkItemValue();
        if (TextUtils.isEmpty(tips)) {
            // ok
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确认保存？")
                    .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            List<String> list = editItemView.get();
                            Log.d(TAG, "new list is " + list.toString());
                            CustomValueManager.getInstance(getApplicationContext()).setFiledValues(mEditFiled, list);
                            Toast.makeText(CustomEditActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).show();
        } else {
            // something wrong
            new AlertDialog.Builder(this)
                    .setTitle("错误提示")
                    .setMessage(tips)
                    .setNegativeButton("我知道了", null)
                    .show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    synchronized (this) {
                        if (operateList.size() > 0) {
                            new AlertDialog.Builder(this)
                                    .setTitle("提示")
                                    .setMessage("有修改，是否需要保存")
                                    .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            onClick_doSave(null);
                                        }
                                    })
                                    .setNegativeButton("算了", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            CustomEditActivity.this.finish();
                                        }
                                    })
                                    .show();
                            return true;
                        }
                    }
                    break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onClick_toggleExpand(View v) {
        editItemView.toggleExpand();
    }

    private static final int MAX_OPERATE_HISTORY = 10;
    private List<Runnable> operateList = new ArrayList<>();

    @Override
    public synchronized void onOperate(int opt, Runnable onRestoreRunnable) {
        if (operateList.size() >= MAX_OPERATE_HISTORY) {
            operateList.remove(0);
        }
        operateList.add(onRestoreRunnable);
        Log.d(TAG, String.format("onOperate() opt=%d, size=%d", opt, operateList.size()));
        updateChildUi();
    }

    public synchronized void doRestoreOperate(View v) {
        Log.d(TAG, "doRestoreOperate()");
        if (operateList.size() > 0) {
            // 最末尾取，最新的
            Runnable r = operateList.remove(operateList.size() - 1);
            r.run();
        }
        Log.d(TAG, "doRestoreOperate() after size=" + operateList.size());
        updateChildUi();
    }
}
